<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="行政区划管理"></n-card>
    </div>
    <n-card :bordered="false" class="mt-4 proCard">
      <BasicTable :columns="columns" :request="loadDataTable" :row-key="(row) => row.id" ref="actionRef"
        :actionColumn="actionColumn" @update:checked-row-keys="onCheckedRow" :bordered="false" allow-checking-not-loaded
        @load="onLoad">
        <template #tableTitle>
          <n-space>
            <n-button type="primary" :on-click="handleEdit.bind(null, {}, 1)">
              <template #icon>
                <n-icon>
                  <PlusOutlined />
                </n-icon>
              </template>
              添加行政区划
            </n-button>
            <n-button type="primary" :loading="btnLoading" :on-click="refreshCache">
              <template #icon>
                <n-icon>
                  <SyncOutlined />
                </n-icon>
              </template>
              刷新缓存
            </n-button>
          </n-space>
        </template>
        <template #action>
          <TableAction />
        </template>
      </BasicTable>
    </n-card>

    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" :title="editTitle" style="width: 720px;">
      <n-form :model="fromValues" :rules="rules" ref="formRef" label-placement="top" :label-width="120" class="py-4">
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="12" label="城市名" path="cityName">
            <n-input maxlength="64" show-count placeholder="请输入城市名" v-model:value="fromValues.cityName" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="简称" path="shortName">
            <n-input maxlength="32" show-count placeholder="请输入简称" v-model:value="fromValues.shortName" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="级别" path="depth">
            <n-input-number style="width: 100%;" placeholder="请输入级别" v-model:value="fromValues.depth" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="城市编码" path="cityCode">
            <n-input maxlength="4" show-count placeholder="请输入城市编码" v-model:value="fromValues.cityCode" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="行政区域编码" path="zipCode">
            <n-input maxlength="6" show-count placeholder="请输入行政区域编码" v-model:value="fromValues.zipCode" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="全名称" path="mergerName">
            <n-input maxlength="100" show-count placeholder="请输入全名称" v-model:value="fromValues.mergerName" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="经度" path="longitude">
            <n-input maxlength="16" show-count placeholder="请输入经度" v-model:value="fromValues.longitude" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="纬度" path="latitude">
            <n-input maxlength="16" show-count placeholder="请输入纬度" v-model:value="fromValues.latitude" />
          </n-form-item-gi>
          <n-form-item-gi :span="24" label="拼音" path="pinyin">
            <n-input maxlength="64" show-count placeholder="请输入全名称" v-model:value="fromValues.pinyin" />
          </n-form-item-gi>
        </n-grid>
      </n-form>
      <div style="justify-content: end;display: flex;">
        <n-space>
          <n-button ghost icon-placement="left" @click="handleCloseModel">
            取消
          </n-button>
          <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">提交</n-button>
        </n-space>
      </div>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, h, reactive } from 'vue';
import { useMessage, useDialog, type FormRules } from 'naive-ui';
import { BasicTable, TableAction } from '@/components/Table';
import { columns } from './columns';
import { regionPageTree, saveRegion, updateRegion, removeRegion, loadProvinces, regionChildren } from '@/api/system/region';
import { DeleteOutlined, EditOutlined, PlusOutlined, SyncOutlined } from '@vicons/antd';
import { ResultEnum } from '@/enums/httpEnum';
const message = useMessage();
const dialog = useDialog();
const formBtnLoading = ref(false);
const actionRef = ref();
const editTitle = ref('');
const isAdd = ref(1);
const showModal = ref(false);
const formRef: any = ref(null);
const btnLoading = ref(false);
let fromValues = reactive({
  id: null,
  /**城市名称*/
  cityName: '',
  /**父级ID*/
  parentId: 100000,
  /**简称*/
  shortName: '',
  /**级别*/
  depth: 1,
  /**城市编码*/
  cityCode: '',
  /**行政区域编码*/
  zipCode: '',
  /**全名称*/
  mergerName: '',
  /**经度*/
  longitude: '',
  /**纬度*/
  latitude: '',
  /**拼音*/
  pinyin: '',
});
const rules: FormRules = {
  cityName: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入城市名称',
  },
  shortName: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入简称',
  },
  depth: {
    type: 'number',
    required: true,
    message: '请输入级别',
    trigger: ['blur', 'change'],
  },
  mergerName: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入全名称',
  },
  longitude: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入经度',
  },
  latitude: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入纬度',
  },
  pinyin: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入拼音',
  },
};
const loadDataTable = async (res: any) => {
  return await regionPageTree(res);
};
/**
 * 子集数据查询
 * @param row 
 */
const onLoad = async (row: Record<string, unknown>) => {
  const data = await regionChildren({ parentId: row.id });
  return new Promise<void>((resolve) => {
    row.children = data;
    resolve();
  })
}
const actionColumn = reactive({
  width: 250,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record) {
    return h(TableAction as any, {
      style: 'text',
      actions: createActions(record),
    });
  },
});

function createActions(record) {
  return [
    {
      label: '新增',
      type: 'success',
      icon: PlusOutlined,
      onClick: handleEdit.bind(null, record, 3),
      ifShow: () => {
        return true;
      },
      //auth: ['basic_list'],
    },
    {
      label: '编辑',
      type: 'primary',
      icon: EditOutlined,
      onClick: handleEdit.bind(null, record, 2),
      ifShow: () => {
        return true;
      },
      //auth: ['basic_list'],
    },
    {
      label: '删除',
      type: 'error',
      // 配置 color 会覆盖 type
      color: 'red',
      icon: DeleteOutlined,
      onClick: handleDelete.bind(null, record),
      // 根据业务控制是否显示 isShow 和 auth 是并且关系
      ifShow: () => {
        return true;
      },
      // 根据权限控制是否显示: 有权限，会显示，支持多个
      //auth: ['basic_list'],
    },
  ];
}
function onCheckedRow(rowKeys: any[]) {
  console.log(rowKeys);
}

function reloadTable() {
  actionRef.value.reload();
}
/**
 * 新增，编辑，新增子节点
 * @param record 
 * @param addStatus 
 */
function handleEdit(record: Recordable, addStatus: number) {
  showModal.value = true;
  isAdd.value = addStatus;
  resetFrom();
  console.log('numbernumbernumbernumber', addStatus)
  if (addStatus === 1) {
    editTitle.value = `新增行政区划`;
  }
  if (addStatus === 2) {
    editTitle.value = `编辑 ${record.cityName}`;
    fromValues = Object.assign(fromValues, record);
  }
  if (addStatus === 3) {
    editTitle.value = `新增 ${record.cityName}子节点`;
    fromValues = Object.assign(fromValues, { parentId: record.id });
  }
}
function resetFrom() {
  fromValues = Object.assign(fromValues, {
    id: null,
    /**城市名称*/
    cityName: '',
    /**父级ID*/
    parentId: 0,
    /**简称*/
    shortName: '',
    /**级别*/
    depth: 1,
    /**城市编码*/
    cityCode: '',
    /**行政区域编码*/
    zipCode: '',
    /**全名称*/
    mergerName: '',
    /**经度*/
    longitude: '',
    /**纬度*/
    latitude: '',
    /**拼音*/
    pinyin: '',
  });
}
/**
 * 新增编辑提交数据
 * @param e 
 */
function confirmForm(e: any) {
  e.preventDefault();
  formRef.value.validate(async (errors) => {
    if (!errors) {
      formBtnLoading.value = true;
      let data: any;
      if (isAdd.value === 2) {
        data = await updateRegion(fromValues);
      } else {
        data = await saveRegion(fromValues);
      }
      if (data.code !== ResultEnum.SUCCESS) {
        const resultMsg = data.data ? data.data : '';
        message.error(data.mesg + '-' + resultMsg);
        formBtnLoading.value = false;
      }
      if (data.code === ResultEnum.SUCCESS) {
        message.success(data.mesg);
        showModal.value = false;
        resetFrom();
        reloadTable();
      }
      formBtnLoading.value = false;
    } else {
      message.error('请填写完整信息');
    }
    formBtnLoading.value = false;
  });
}
/**
 * 新增编辑关闭model
 */
function handleCloseModel() {
  resetFrom();
  showModal.value = false;
}
/**
 * 删除确认
 * @param record 
 */
function handleDelete(record: Recordable) {
  dialog.warning({
    title: '警告',
    content: `确定删除${record.cityName}吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const data = await removeRegion({ id: record.id });
      if (data.code !== ResultEnum.SUCCESS) {
        const resultMsg = data.data ? data.data : '';
        message.error(data.mesg + '-' + resultMsg);
      }
      if (data.code === ResultEnum.SUCCESS) {
        message.success(data.mesg);
        showModal.value = false;
        reloadTable();
      }
    },
  })
}
async function refreshCache() {
  btnLoading.value = true;
  const data = await loadProvinces({});
  if (data.code !== ResultEnum.SUCCESS) {
    const resultMsg = data.data ? data.data : '';
    message.error(data.mesg + '-' + resultMsg);
    btnLoading.value = false;
  }
  if (data.code === ResultEnum.SUCCESS) {
    message.success(data.mesg);
    btnLoading.value = false;
  }
}
</script>

<style lang="less" scoped></style>
